<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        #myTable {
            border-collapse: collapse; /*合并单元格边框*/
            width: 100%;
        }

        #myTable th, #myTable td {
            border: 1px solid #ddd; /*设置单元格边框*/
            padding: 8px; /*设置单元格内边距*/
            text-align: left; /*设置文本对齐方式*/
        }

        #myTable th {
            background-color: #4CAF50; /*设置表头背景颜色*/
            color: white; /*设置表头文本颜色*/
        }

    </style>

</head>
<body>
    <table id="myTable">
        <tr>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <tr>
            <td>小明</td>
            <td>18</td>
        </tr>
        <tr>
            <td>小红</td>
            <td>20</td>
        </tr>
    </table>
    <div id="table-container"></div>
    <script>
        // 创建表格元素
        var table = document.createElement("table");

        // 创建表头行和单元格，并添加到表头部分
        var headerRow = document.createElement("tr");
        var header1 = document.createElement("th");
        var header2 = document.createElement("th");
        var header3 = document.createElement("th");
        header1.textContent = "姓名";
        header2.textContent = "年龄";
        header3.textContent = "性别";
        headerRow.appendChild(header1);
        headerRow.appendChild(header2);
        headerRow.appendChild(header3);
        var thead = document.createElement("thead");
        thead.appendChild(headerRow);
        table.appendChild(thead);

        // 创建数据行和单元格，并添加到表格主体部分
        var row1 = document.createElement("tr");
        var cell11 = document.createElement("td");
        var cell12 = document.createElement("td");
        var cell13 = document.createElement("td");
        cell11.textContent = "张三";
        cell12.textContent = "25";
        cell13.textContent = "男";
        row1.appendChild(cell11);
        row1.appendChild(cell12);
        row1.appendChild(cell13);
        var row2 = document.createElement("tr");
        var cell21 = document.createElement("td");
        var cell22 = document.createElement("td");
        var cell23 = document.createElement("td");
        cell21.textContent = "李四";
        cell22.textContent = "30";
        cell23.textContent = "女";
        row2.appendChild(cell21);
        row2.appendChild(cell22);
        row2.appendChild(cell23);
        var tbody = document.createElement("tbody");
        tbody.appendChild(row1);
        tbody.appendChild(row2);
        table.appendChild(tbody);

        // 将表格添加到页面中的某个元素
        var container = document.getElementById("table-container");
        container.appendChild(table);

    </script>
</body>
</html>

